import axios from 'axios';
import FingerprintJS from '@fingerprintjs/fingerprintjs';

const instance = axios.create({
  baseURL: 'https://hsgc.hairuige.com', 
  timeout: 100000,
});


// 获取 FingerprintJS 的浏览器指纹
const getFingerprint = async () => {
  // const fp = await FingerprintJS.load();
  // const result = await fp.get();
  // return result.visitorId;
   const canvas = document.createElement("canvas");
      const gl =
        canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
      if (!gl) {
        return null;
      }
      const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
      const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
      const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
    
      // 收集 WebGL 参数
      const webGLInfo = [
        gl.getParameter(gl.VERSION),
        gl.getParameter(gl.SHADING_LANGUAGE_VERSION),
        gl.getParameter(gl.VENDOR),
        vendor,
        renderer,
      ];
    
      // 对结果进行哈希处理
      let hash = 0;
      const str = webGLInfo.join(" ");
      for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i);
        hash = hash & hash;
      }
      return hash.toString();
};

// 请求拦截器
instance.interceptors.request.use(
  async function (config) {
    const apikey = await getFingerprint();
    if (apikey) {
      if (!config.params) {
        config.params = {};
      }
      config.params['apikey'] = apikey;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    console.error('请求发生错误：', error.response || error.message);
    return Promise.reject(error);
  }
);

export default instance;
